package dao

import (
	m "cat_mouse/core/model"
	"cat_mouse/infra/dao"
	"cat_mouse/infra/model"
	"cat_mouse/infra/utils"
	"sync"
	"time"
)

var (
	validCodeDao     *ValidCodeDao
	validCodeDaoOnce sync.Once
)

type ValidCodeDao struct {
	dao.BaseDao
}

func (v *ValidCodeDao) GetByExpireAt(phone string, expireAt time.Time) ([]*m.ValidCode, error) {
	var (
		rows = make([]*m.ValidCode, 0)
		err  error
	)
	err = model.DB.Model(&m.ValidCode{}).Where(
		"phone = ? and expire_at > ?", phone, utils.TimeToString(expireAt)).Scan(&rows).Error
	return rows, err
}

func (v *ValidCodeDao) DelByExpireAt(expireAt time.Time) error {
	return model.DB.Where("expire_at < ?", utils.TimeToString(expireAt)).Delete(&m.ValidCode{}).Error
}

func (v *ValidCodeDao) GetByPhone(phone string) (*m.ValidCode, error) {
	var (
		validCode m.ValidCode
		err       error
	)
	err = model.DB.Where("phone = ?", phone).Order("created_time desc").First(&validCode).Error
	return &validCode, err
}

func NewValidCodeDao() *ValidCodeDao {
	validCodeDaoOnce.Do(func() {
		validCodeDao = &ValidCodeDao{}
	})
	return validCodeDao
}
